<template>
  <el-container>
    <!-- 添加窗口 -->
    <el-dialog v-if="addHackReset" width="900px" title="选择套餐" :visible.sync="addFormVisible" @close="addClose">
      <el-form ref="addFormRef" style="margin: 30px 0;" :model="addForm" :rules="productRules" label-width="80px">
        <el-row>
          <el-col :span="14">
            <el-form-item prop="productId" label="选择套餐">
              <search-options ref="addProductRef" :tips-text="'请选择套餐名称'" :options-style="'width: 80%'" :request="'product'"
                :fixed-params="mealParams" @getValue="addQueryProduct" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="productId" label="是否单次">
              <el-radio v-model="addFrequency" label="1" @change="addFrequencyFn">单次</el-radio>
              <el-radio v-model="addFrequency" label="2" @change="addFrequencyFn">多次</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="addFrequency!=1">
            <el-form-item label="配送次数">
              <el-select v-model="addForm.quantity" style="width: 80%;" placeholder="请选择配送次数" @change="selectMaxTime(addForm.quantity,0)">
                <el-option v-for="item in 24" :key="item" :label="item+1" :value="item+1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-show="Number(addForm.quantity) > 1" label="次数">
          <el-pagination layout="pager" :total="Number(addForm.quantity) * 10" @current-change="addFormQuantityClick"
            style="justify-content: left;" />
        </el-form-item>
        <el-form-item style="position: relative" label="选择商品">
          <span class="el-icon-plus add-add-click" style="position: absolute; left: -25px; top: 25px; color: #409EFF;"
            @click="addDataItem" />
          <el-table v-for="(item, index) in addForm.itemList" v-show="addFormCurrentIndex == index" :key="index" ref="addTableFormRef"
            :class="'add-form-css' + index" :data="item" stripe border style="width: 100%">
            <el-table-column label="商品">
              <template slot-scope="scope">
                <!-- <el-form-item style="margin-bottom: 0;" :prop="`itemList[${addFormCurrentIndex}][${scope.$index}].productName`" :rules="productRules.productName"> -->
                <el-form-item style="margin-bottom: 0;">
                  <el-select v-model="item[scope.$index].productId" style="width: 100%;" placeholder="请选择对应商品名称"
                    filterable :filter-method="queryProduct" @change="addFromAddItemList(scope.$index, scope.row.productId)">
                    <el-option v-for="item in productIdOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" width="82">
              <template slot-scope="scope">
                <img :key="Math.random()" style="width: 60px; height: 60px; vertical-align:middle; overflow: hidden;background-color: #F2F6FC;"
                  :src="scope.row.productThumbnail" alt="">
              </template>
            </el-table-column>
            <el-table-column label="价格" width="110" prop="productPrice" />
            <el-table-column label="单位" width="80" prop="unit" />
            <el-table-column label="数量" width="110" prop="convRate">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.convRate" type="number" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                  <a v-show="addForm.itemList[addFormCurrentIndex].length > 1" @click="addFromDelItemList(scope.$index)">
                    <i style="color: #F56C6C" class="el-icon-delete" />
                  </a>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" v-permission="['meal.add']" :disabled="addClicked" @click="addClick">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改窗口 -->
    <el-dialog v-if="editHackReset" width="900px" title="选择套餐" :visible.sync="editFormVisible" @close="editClose">
      <el-form ref="editFormRef" style="margin: 30px 0;" :model="editForm" :rules="productRules" label-width="80px">
        <el-row>
          <el-col :span="14">
            <el-form-item prop="productId" label="选择套餐">
              <search-options ref="editProductRef" :tips-text="'请选择套餐名称'" :options-style="'width: 80%'" :request="'product'"
                disabled :find-value="[{name: editForm.productName, id: editForm.productId}]" :fixed-params="mealParams"
                @getAllData="editQueryProduct" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="productId" label="是否单次">
              <el-radio v-model="editFrequency" label="1" @change="editFrequencyFn">单次</el-radio>
              <el-radio v-model="editFrequency" label="2" @change="editFrequencyFn">多次</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="editFrequency!=1">
            <el-form-item label="配送次数">
              <el-select v-model="editForm.quantity" style="width: 80%;" placeholder="请选择配送次数" @change="selectMaxTime(editForm.quantity,1)">
                <el-option v-for="item in 48" :key="item" :label="item+1" :value="item+1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row v-if="editFrequency!=1">
          <el-col :span="14">
            <el-form-item label="配送次数">
              <el-select v-model="editForm.quantity" style="width: 80%;" placeholder="请选择配送次数" @change="selectMaxTime(editForm.quantity,1)">
                <el-option v-for="item in 24" :key="item" :label="item+1" :value="item+1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item v-show="Number(editForm.quantity) > 1" label="次数">
          <el-pagination layout="pager" :total="Number(editForm.quantity) * 10" @current-change="editFormQuantityClick"
            style="justify-content: left;" />
        </el-form-item>
        <el-form-item style="position: relative;" label="选择商品">
          <span class="el-icon-plus edit-add-click" style="position: absolute; left: -25px; top: 25px; color: #409EFF;"
            @click="editDataItem" />
          <el-table v-for="(item, index) in editForm.itemList" v-show="editFormCurrentIndex == index" :key="index" ref="editTableFormRef"
            :class="'edit-form-css' + index" :data="item" stripe border style="width: 100%">
            <el-table-column prop="productName" label="商品">
              <template slot-scope="scope">
                <!-- <el-form-item style="margin-bottom: 0;" :prop="`itemList[${scope.$index}].productName`" :rules="productRules.productName"> -->
                <el-form-item style="margin-bottom: 0;">
                  <el-select v-model="item[scope.$index].productId" style="width: 100%;" placeholder="请选择对应商品名称"
                    filterable :filter-method="queryProduct" @change="editFromAddItemList(scope.$index, scope.row.productId)">
                    <el-option v-for="item in productIdOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" width="82">
              <template slot-scope="scope">
                <img :key="Math.random()" style="width: 60px; height: 60px; vertical-align:middle; overflow: hidden;background-color: #F2F6FC;"
                  :src="scope.row.productThumbnail" alt="">
              </template>
            </el-table-column>
            <el-table-column label="价格" width="110" prop="productPrice" />
            <el-table-column label="单位" width="80" prop="unit" />
            <el-table-column label="数量" width="110" prop="convRate">
              <template slot-scope="scope">
                <el-input v-model="scope.row.convRate" type="number" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                  <a v-show="editForm.itemList[editFormCurrentIndex].length > 1" @click="editFromDelItemList(scope.$index)">
                    <i style="color: #F56C6C" class="el-icon-delete" />
                  </a>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" v-permission="['meal.edit']" :loading="editClicked" @click="editClick">确 定</el-button>
      </div>
    </el-dialog>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div style="display: flex;flex-direction: row;justify-content: space-between;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: flex-end;">
            <div class="report_header_query" v-if="mchType==0||mchType==3">
              <el-select v-model="query.sysMchId" clearable placeholder="请选择商户" filterable value-key="id"
                :filter-method="querySysmch" @change="changeSysMch">
                <el-option v-for="item in mchIdOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="report_header_query">
              <el-select v-model="productName" value-key="id" clearable placeholder="请选择商品" style="width: 100%"
                filterable @focus="getProductList('')" :filter-method="serachProduct" @change="changeProduct">
                <el-option style="width:650px" v-for="item in productOptions" :key="item.id" :label="item.name" :value="item">
                  <div style="display: flex">
                    <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                    <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toAddProduct">搜索商品</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
            </div>
          </div>
          <div>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" v-permission="['meal.add']"
            @click="addShowDialog">新增</el-button>
          </div>
        </div>
      </div>
    </el-header>
    <div class="pd10">
      <el-table v-loadMore="[payLoads,'empty-barrel']" :data="emptyBarrelList" border stripe :height="curHeight" style="width: 100%">
        <el-table-column label="缩略图" align="center" width="80">
          <template slot-scope="scope">
            <img style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;" :src="scope.row.productThumbnail"
              alt="">
          </template>
        </el-table-column>
        <el-table-column label="编号" align="left" prop="sn" />
        <el-table-column label="套餐名称" align="left" prop="productName" />
        <el-table-column label="套餐价格" align="left" prop="productPrice" />
        <el-table-column label="配送次数" width="80" prop="quantity" />
        <el-table-column label="单位" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center" prop="isMarketable">
          <template slot-scope="scope">
            <el-tag type="success">
              <span>{{ scope.row.isMarketable | watchType }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="70" prop="orders" :render-header="ordersIcons">
          <template slot-scope="scope">
            <el-input v-model="scope.row.orders" @blur="bulrOrders(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="功能" align="center" fixed="right" width="80">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isMarketable" v-permission="['meal.down']" type="primary" size="mini" @click="releaseEmptyBarrel(scope.row)">
              下架
            </el-button>
            <el-button v-else v-permission="['meal.up']" type="danger" size="mini" @click="releaseEmptyBarrel(scope.row)">
              上架
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip v-permission="['meal.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                <a @click="editShowDialog(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit" />
                </a>
              </el-tooltip>
              <el-tooltip v-permission="['meal.del']" class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="deleteEmptyBarrel(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete" />
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="选择商品" :visible.sync="orderVisible" width="68%" v-el-drag-dialog :before-close="orderClose">
      <div style="position: relative;">
        <productTable ref="productList" @orderClose="orderClose" @doubleClick="doubleClick" @addClick="addProduct"></productTable>
      </div>
    </el-dialog>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadEmptyBarrel" />
    </el-footer>

  </el-container>
</template>

<script>
  import loadMore from '@/utils/loadMore.js'
  import productTable from '@/components/ProductList/productList'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {
    list,
    save,
    find,
    update,
    del
  } from '@/api/emptyBarrel'
  import {
    list as productList,
    updateProduct
  } from '@/api/product'
  import Pagination from '@/components/Pagination'
  import searchOptions from '@/components/searchOptions'
  import utils from '../../utils/utils.js'
  import {
    getInfo,
    list as sysMchList
  } from '@/api/sysMch'

  export default {
    name: 'MealList',
    directives: {
      permission,
      loadMore,
      elDragDialog
    },
    components: {
      Pagination,
      searchOptions,
      productTable
    },
    filters: {
      watchType(val) {
        if (val === false) {
          return '未上架'
        } else if (val === true) {
          return '已上架'
        }
      }
    },
    data() {
      return {
        mchIdOptions: [],
        mchType: '',
        query: {
          productId: '',
          sysMchId: '',
        },
        keyword: {
          productId: ''
        },
        productOptions: [],
        addFrequency: '1',
        editFrequency: '1',
        times: [],
        queryType: true,
        productName: '',
        pageNum: 1,
        pageSize: 20,
        orderVisible: false,
        total: 0,
        curHeight: null,
        payLoads: '',
        productMark: false, // 防抖
        productIdOptions: [],
        emptyBarrelList: [],
        mealParams: {
          subType: 1,
          type: 1,
          isList: true
        },
        productParams: {
          name: '',
          type: 0,
          isList: true
        },
        addFormVisible: false,
        addFormCurrentIndex: 0,
        addClicked: false,
        addForm: {
          quantity: '',
          productId: '',
          itemList: [],
          type: 1
        },
        addHackReset: false,
        editFormVisible: false,
        editFormCurrentIndex: 0,
        editClicked: false,
        editForm: {
          id: '',
          productId: '',
          itemList: [],
          type: 1,
          quantity: ''
        },
        editHackReset: false,
        productRules: {
          quantity: [{
            required: true,
            message: '请输入配送次数',
            trigger: 'blur'
          }],
          productId: [{
            required: true,
            message: '请选择商品名称',
            trigger: 'blur'
          }],
          productName: [{
            required: true,
            message: '请选择商品名称',
            trigger: 'blur'
          }],
          productPrice: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          convRate: [{
            required: true,
            message: '请输入捆绑系数',
            trigger: 'blur'
          }]
        }
      }
    },
    activated() {
      this.payLoads = new Date().getTime()
    },
    created() {
      this.loadSysmch('')
      this.loadMch()
      this.loadEmptyBarrel()
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      loadSysmch(query) {
        sysMchList({
          name: query
        }).then(res => {
          this.mchIdOptions = res.data.data.filter(val => {
            return val.mchType === 3 || val.mchType === 1
          })
        }).catch(err => {
          console.log(err)
        })
      },
      changeSysMch() {
        this.loadEmptyBarrel()
      },
      querySysmch(query) {
        this.loadSysmch(query)
      },
      loadMch() {
        getInfo().then(res => {
          this.mchType = res.data.mchType
        })
      },
      addProduct(data) {
        if (data.length > 1) {
          this.productName = data[0].name
          this.query.productId = data[0].id
          this.orderVisible = false
          this.$message({
            message: '只能查询一个商品',
            type: 'warning'
          })
        } else {
          this.productName = data[0].name
          this.query.productId = data[0].id
        }
      },
      queryClick() {
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadEmptyBarrel()
      },
      doubleClick(val) {
        this.productName = val.name
        this.query.productId = val.id
        this.orderVisible = false
      },
      resetClick() {
        this.productName = ''
        this.query.productId = '';
        this.keyword = this.query;
        this.pageNum = 1;

      },
      serachProduct(query) {
        this.getProductList(query)
      },
      orderClose() {
        this.orderVisible = false;
      },
      changeProduct(data) {
        if (!utils.isNull(data)) {
          this.productName = data.name
          this.query.productId = data.id
        } else {
          this.productName = ''
          this.query.productId = ''
        }
      },
      getProductList(query) {
        let param = new URLSearchParams()
        param.append('name', query)
        productList(param).then(res => {
          this.productOptions = res.data.data
        })
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266 //减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220 //减去页面上固定高度height
        }
      },
      toAddProduct() {
        this.orderVisible = true;

      },
      selectMaxTime(data, type) {
        console.log(data + '----------' + type)
        this.times = []
        if (type === 0) {
          if (data > 24) {
            data = 24
            this.addForm.quantity = 24
          }
          for (let i = 0; i < data; i++) {
            this.addForm.itemList.push([{
              convRate: 1,
              groupId: 1
            }])
          }
          if (this.addFormCurrentIndex > this.addForm.quantity - 1) {
            this.addFormCurrentIndex = this.addForm.quantity - 1
          }
          this.addForm.itemList.length = this.addForm.quantity
        } else if (type === 1) {
          if (data > 24) {
            data = 24
            this.editForm.quantity = 24
          }
          for (let i = 0; i < data; i++) {
            this.editForm.itemList.push([{
              convRate: 1,
              groupId: 1
            }])
          }
          if (this.editFormCurrentIndex > this.editForm.quantity - 1) {
            this.editFormCurrentIndex = this.editForm.quantity - 1
          }
          this.editForm.itemList.length = this.editForm.quantity
        }
        if (data !== null || data !== '' || data > 0) {
          for (var i = 1; i <= data; i++) {
            this.times.push(i)
          }
        } else {
          this.times.push(0)
        }
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              _this.curHeight = h - 266 // 减去页面上固定高度height
            } else {
              _this.curHeight = h - 220 // 减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220 // 减去页面上固定高度height
      },
      loadEmptyBarrel() {
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('mchId', this.query.sysMchId)
        params.append('pageSize', this.pageSize)
        params.append('productId', this.keyword.productId)
        params.append('type', 1)
        list(params).then(res => {
          console.log(res)
          this.emptyBarrelList = res.data.data
          this.total = res.data.total
        }).catch(() => {})
      },
      queryProduct(query) {
        clearTimeout(this.productMark)
        this.productMark = setTimeout(() => {
          this.productIdOptions = []
          this.productParams.name = query
          productList(this.productParams).then(res => {
            this.productIdOptions = res.data.data
            if (utils.isNull(this.editForm.itemList)) {
              return
            }
            this.editForm.itemList.forEach(list => { // 让每一项与列表比对,找不到则添加进去
              list.forEach(item => {
                const notFound = this.productIdOptions.find(val => {
                  return val.id == item.productId
                }) // 找到列表里没有的数据
                if (!notFound && item.productId !== '') {
                  const obj = {
                    name: item.productName,
                    id: item.productId,
                    thumbnail: item.productThumbnail,
                    price: item.productPrice,
                    unit: item.unit
                  }
                  this.productIdOptions.unshift(obj) // 把没有的数据添加到列表里
                }
              })
            })
            /* this.editForm.itemList[this.editFormCurrentIndex].forEach((item, index) => {
              const notFound = this.productIdOptions.find(val => { return val.id == item.productId }) // 找到列表里没有的数据
              if (!notFound && item.productId !== '') {
                const obj = {
                  name: item.productName,
                  id: item.productId
                }
                this.productIdOptions.unshift(obj) // 把没有的数据添加到列表里
              }
            }) */
          }).catch(err => {
            console.log(err)
          })
        }, 300)
      },
      addQueryProduct(value) { // 添加的查询商品
        this.addForm.productId = value
      },
      addShowDialog() {
        this.addFrequency = '1'
        this.addForm = {
          productId: '',
          type: 1,
          quantity: '1',
          itemList: [
            [{
              productName: '',
              convRate: 1,
              groupId: 1
            }]
          ]
        }
        if (this.addForm.itemList.length == 1) {
          this.productParams.type = ''
        } else {
          this.productParams.type = 0
        }
        this.queryProduct()
        this.$nextTick(() => { // 避免数据更新页面未刷新
          this.addHackReset = true
        })
        setTimeout(() => {
          this.$refs.addProductRef.resetValue()
        }, 200)
        this.addFormVisible = true
        this.setAddClickHeight(0)
      },
      addFromAddItemList(index, productId) {
        // 给对应itemList赋值对应属性
        const OptionsIndex = this.productIdOptions.find(val => {
          return val.id == productId
        })
        this.addForm.itemList[this.addFormCurrentIndex][index].productName = OptionsIndex.name
        this.addForm.itemList[this.addFormCurrentIndex][index].productPrice = OptionsIndex.price
        this.addForm.itemList[this.addFormCurrentIndex][index].productThumbnail = OptionsIndex.thumbnail
        this.addForm.itemList[this.addFormCurrentIndex][index].unit = OptionsIndex.unit
      },
      addDataItem() {
        const obj = {
          productId: '',
          productName: '',
          productPrice: '',
          convRate: 1,
          groupId: 1
        }
        this.addForm.itemList[this.addFormCurrentIndex].push(obj)
        this.setAddClickHeight(0)
      },
      addFormQuantityClick(index) {
        this.addFormCurrentIndex = index - 1
        this.setAddClickHeight(0)
      },
      addClick() { // 新增
        this.$refs['addFormRef'].validate((valid) => {
          this.addClicked = true
          if (valid) {
            const params = {
              productId: this.addForm.productId,
              type: this.addForm.type,
              quantity: this.addForm.quantity
            }
            const itemList = []
            // 拿到所有itemList
            for (let i = 0; i < this.addForm.itemList.length; i++) {
              for (let j = 0; j < this.addForm.itemList[i].length; j++) {
                if (utils.isNull(this.addForm.itemList[i][j].productName)) {
                  this.$message({
                    message: '请填写商品名称',
                    type: 'warning'
                  })
                  return
                } else if (utils.isNull(this.addForm.itemList[i][j].convRate)) {
                  this.$message({
                    message: '请填写数量',
                    type: 'warning'
                  })
                  return
                }
                this.addForm.itemList[i][j].groupId = i + 1
                itemList.push(this.addForm.itemList[i][j])
              }
            }
            itemList.forEach((item, index) => { // 暂时去掉单位
              delete itemList[index].unit
            })
            params.itemList = itemList
            console.log(params, 'params')
            save(params).then(res => {
              console.log(res)
              this.loadEmptyBarrel()
              this.addFormVisible = false
              this.addClicked = false
            }).catch(() => {
              this.addClicked = false
            })
          } else {
            return false
          }
          this.addClicked = false
        })
        this.addClicked = false
      },
      addFromDelItemList(index) { // 删除itemList单项
        this.addForm.itemList[this.addFormCurrentIndex].splice(index, 1)
        this.setAddClickHeight(0)
      },
      addClose() {
        this.addForm.itemList = []
        this.addFormCurrentIndex = 0
        this.addHackReset = false
      },
      addFrequencyFn(e) {
        if (e == 1) {
          this.addForm.quantity = '1'
          this.addForm.itemList.length = 1
          this.addFormCurrentIndex = 0
          this.productParams.type = ''
        } else {
          this.addForm.quantity = '2'
          this.addForm.itemList[1] = ([{
            convRate: 1,
            groupId: 1
          }])
          this.productParams.type = 0
        }
        this.queryProduct()
        this.setAddClickHeight(0)
      },
      editFormQuantityClick(index) {
        this.editFormCurrentIndex = index - 1
        this.setAddClickHeight(1)
      },
      editShowDialog(row) { // 编辑
        find(row.id).then(res => {
          console.log(res, 'res')
          this.editForm = res.data.bom
          const tempItemList = []
          for (let i = 0; i < this.editForm.quantity; i++) {
            tempItemList[i] = []
            for (let j = 0; j < this.editForm.itemList.length; j++) {
              if (Number(this.editForm.itemList[j].groupId) === i + 1) {
                tempItemList[i].push(this.editForm.itemList[j])
              }
            }
          }
          this.editForm.itemList = tempItemList
          if (this.editForm.quantity > 1) {
            this.editFrequency = '2'
          } else {
            this.editFrequency = '1'
          }
          if (this.editForm.itemList.length == 1) {
            this.productParams.type = ''
          } else {
            this.productParams.type = 0
          }
          this.queryProduct()
          this.setAddClickHeight(1)
          this.$nextTick(() => { // 避免数据更新页面未刷新
            this.editHackReset = true
          })
          this.$refs.editProductRef.queryOptions() // 避免数据更新页面未刷新
        }).catch(() => {})
        this.editFormVisible = true
      },
      editQueryProduct(value) { // 添加的查询商品
        if (utils.isNull(value)) {
          this.editForm.productId = ''
          this.editForm.productName = ''
        } else {
          this.editForm.productId = value.id
          this.editForm.productName = value.name
        }
      },
      editDataItem() {
        const obj = {
          productId: '',
          productName: '',
          productPrice: '',
          convRate: 1,
          groupId: 1
        }
        this.editForm.itemList[this.editFormCurrentIndex].push(obj)
        this.setAddClickHeight(1)
      },
      editFromAddItemList(index, productId) {
        // 给对应itemList赋值对应属性
        const OptionsIndex = this.productIdOptions.find(val => {
          return val.id == productId
        })
        this.editForm.itemList[this.editFormCurrentIndex][index].productName = OptionsIndex.name
        this.editForm.itemList[this.editFormCurrentIndex][index].productPrice = OptionsIndex.price
        this.editForm.itemList[this.editFormCurrentIndex][index].productThumbnail = OptionsIndex.thumbnail
        this.editForm.itemList[this.editFormCurrentIndex][index].unit = OptionsIndex.unit
      },
      editClick() { // 修改
        this.$refs['editFormRef'].validate((valid) => {
          if (valid) {
            this.editClicked = true
            const params = {
              id: this.editForm.id,
              productId: this.editForm.productId,
              type: this.editForm.type,
              quantity: this.editForm.quantity
            }
            const itemList = []
            // 拿到所有itemList
            for (let i = 0; i < this.editForm.itemList.length; i++) {
              for (let j = 0; j < this.editForm.itemList[i].length; j++) {
                if (utils.isNull(this.editForm.itemList[i][j].productName)) {
                  this.$message({
                    message: '请填写商品名称',
                    type: 'warning'
                  })
                  return
                } else if (utils.isNull(this.editForm.itemList[i][j].convRate)) {
                  this.$message({
                    message: '请填写数量',
                    type: 'warning'
                  })
                  return
                }
                this.editForm.itemList[i][j].groupId = i + 1
                itemList.push(this.editForm.itemList[i][j])
              }
            }
            itemList.forEach(item => { // 先去掉单位跟sn
              delete item.unit
              delete item.sn
            })
            params.itemList = itemList
            /* params.itemList.map(list => {
              list.forEach(item => {
                delete item.unit
              })
              return list
            }) */
            console.log(params, 'params')
            update(params).then(res => {
              console.log(res)
              this.loadEmptyBarrel()
              this.editFormVisible = false
              this.editClicked = false
            }).catch(() => {
              this.editClicked = false
            })
          } else {
            return false
          }
        })
      },
      editFromDelItemList(index) { // 删除itemList单项
        this.editForm.itemList[this.editFormCurrentIndex].splice(index, 1)
        this.setAddClickHeight(1)
      },
      editClose() {
        this.editForm.itemList = []
        this.editFormCurrentIndex = 0
        this.editHackReset = false
      },
      editFrequencyFn(e) {
        if (e == 1) {
          this.editForm.quantity = '1'
          this.editForm.itemList.length = 1
          this.editFormCurrentIndex = 0
          this.productParams.type = ''
        } else {
          this.editForm.quantity = '2'
          this.editForm.itemList[1] = ([{
            convRate: 1,
            groupId: 1
          }])
          this.productParams.type = 0
        }
        this.queryProduct()
        this.setAddClickHeight(0)
      },
      releaseEmptyBarrel(row) { // 上架
        this.$confirm(row.isMarketable ? '确认下架?' : '确认上架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateProduct({
            id: row.productId,
            isMarketable: !row.isMarketable
          }).then(res => {
            console.log(res)
            for (let i = 0; i < this.emptyBarrelList.length; i++) {
              if (this.emptyBarrelList[i].productId == res.data.id) {
                this.emptyBarrelList[i].isMarketable = res.data.isMarketable
              }
            }
            this.$message({
              type: 'success',
              message: row.isMarketable ? '上架成功' : '下架成功'
            })
          }).catch(() => {})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: row.isMarketable ?'已取消下架' : '已取消上架'
          })
        })
      },
      deleteEmptyBarrel(data) {
        console.log(data)
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(res => {
            console.log(res)
            this.emptyBarrelList.forEach((item, index) => {
              if (item.id === data.id) {
                this.emptyBarrelList.splice(index, 1)
              }
            })
            this.$message({
              message: res.content,
              offset: 120,
              center: true
            })
          }).catch(() => {})
        }).catch(() => {})
      },
      ordersIcons(h, {
        column
      }) { // 排序
        const inReview = '点击下方数字区域可直接更改排序。'
        return h('div', [
          h('span', column.label),
          h(
            'el-tooltip', {
              props: {
                placement: 'top'
              }
            },
            [
              h(
                'div', {
                  slot: 'content',
                  style: {
                    width: '200px',
                    whiteSpace: 'normal',
                    'margin-bottom': '10px'
                  }
                },
                inReview
              ),
              h('i', {
                class: 'el-icon-question',
                style: 'color:#888888;margin-left:5px;position:absolute'
              })
            ]
          )
        ])
      },
      bulrOrders(data) {
        console.log(data)
        updateProduct({
          id: data.productId,
          orders: data.product.orders,
          isMarketable: data.isMarketable
        }).then(res => {
          console.log(res)
        }).catch(() => {})
      },
      setAddClickHeight(data) {
        let itemList
        let mask
        let click
        if (data == 0) { // 判断要获取哪个列表的数据
          itemList = this.addForm.itemList[this.addFormCurrentIndex]
          mask = `.add-form-css${this.addFormCurrentIndex}`
          click = '.add-add-click'
        } else {
          itemList = this.editForm.itemList[this.editFormCurrentIndex]
          mask = `.edit-form-css${this.editFormCurrentIndex}`
          click = '.edit-add-click'
        }
        setTimeout(() => {
          // 获取表头的高度
          const tableTopHeight = document.querySelector(`${mask} .el-table__header`).offsetHeight
          const tableItem = document.querySelector(`${mask}`)
          let itemClass // 判断列表是否有数据
          if (tableItem.className.indexOf('el-table--enable-row-transition') > -1) {
            itemClass = '.el-table__row' // 有数据
          } else {
            itemClass = '.el-table__empty-text' // 没数据
          }
          // 获取一行表格高度
          const tableHeight = document.querySelector(`${mask} ${itemClass}`).offsetHeight
          // 获取添加按钮样式
          const addClickStyle = document.querySelector(`${click}`)
          // 获取添加按钮高度
          const addClickHeight = addClickStyle.offsetHeight
          // 设置添加按钮的位置
          const moveHeight = tableTopHeight + ((itemList.length > 0 ? itemList.length - 1 : 0) * tableHeight) + ((
            tableHeight - addClickHeight) / 2)
          /* console.log(tableTopHeight, 'tableTopHeight')
          console.log(tableHeight, 'tableHeight')
          console.log(moveHeight, 'moveHeight') */
          addClickStyle.style.top = moveHeight + 'px'
        }, 100)
      }
    }
  }
</script>
<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  .elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 50%;
    height: 40px
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }

  .popup_content {
    padding-bottom: 0px !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }


  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
